<template>
  <div class="designer-form flex flex-col">
    <div class="flex justify-end mb-4">
      <EditSaveButton
        v-if="auditStatus !== MYINDEX_AUDIT_STATUS.SUCCESS"
        :isEdit="isEdit"
        @buttonClick="handleEdit"
      />
    </div>
    <div class="form-container">
      <el-form
        ref="baseFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        :size="formSize"
        status-icon
        :disabled="disabled"
      >
        <!-- <el-form-item
          label="所在商圈/商场"
          prop="mallName"
          required
          :class="activeMallMode === 'SELECT' ? 'border-0' : 'border-0'"
        >
          <MallSelect :defaultMall="defaultMall" @onChangeMall="handleChangeMall" />
        </el-form-item> -->
        <el-form-item label="身份证图片" class="id-card-upload" required>
          <el-text type="info" size="small">
            1. 请上传中国大陆地区身份证图片，保证图片清晰，身份证大小与图片大小一致
          </el-text>
          <el-text type="info" size="small">2. 请上传身份证正反两面图片</el-text>
        </el-form-item>
        <el-row :gutter="20" class="upload-row">
          <el-col :span="12">
            <el-form-item label="正面" prop="idCardFrontFile" class="upload-item">
              <MultiImageUpload
                v-model="ruleForm.idCardFrontFile"
                :limit="1"
                :isSmallUpload="true"
                :disabled="disabled"
                @uploadSuccess="handleCardFrontFile"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="反面" prop="idCardBackFile" class="upload-item">
              <MultiImageUpload
                v-model="ruleForm.idCardBackFile"
                :limit="1"
                :isSmallUpload="true"
                :disabled="disabled"
                @uploadSuccess="handleCardBackFile"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="form-section">
          <el-form-item label="身份证号码" prop="idNumber" required>
            <el-input v-model="ruleForm.idNumber" placeholder="请输入身份证号码" />
          </el-form-item>
          <el-form-item label="身份证有效期限" required prop="idCardValidity">
            <el-date-picker
              v-model="ruleForm.idCardValidity"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYYMMDD"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
// 请求
import { getIdCardFaceInfo, getIdCardBackInfo } from "@/api/system/common";
import { saveOrUpdateEmployee, getEmployeeEnterInfo } from "@/api/myIndex/index";
// 组件
import MallSelect from "@/views/hide/myIndex/components/mall-select.vue";
import { validateIdCard } from "@/utils/formvalidate";
import { SUBJECT_TYPE_ENUM } from "@/utils/enums/system";
import { storeGetUserType } from "@/utils/auth";
import { useUserStore } from "@/store/modules/user";
import { MYINDEX_AUDIT_STATUS } from "@/views/hide/myIndex/enums/index";
const userStore = useUserStore();
const userId = computed(() => userStore.userInfo.userId);
const userType = storeGetUserType();
const formSize = ref("default");
const proxy = getCurrentInstance();
const emit = defineEmits(["submitSuccess"]);
const handleChangeMall = (val) => {
  ruleForm.mallName = val.mallName;
  ruleForm.mallNameId = val.mallNameId;
};
/**
 * 根据用户角色去获取主体类型列表 - 前端自己存储的枚举
 *
 */
const subjectTypeList = ref([]);
subjectTypeList.value = SUBJECT_TYPE_ENUM[userType];
/***
 * 表单校验管理
 *
 */

const ruleForm = reactive({
  // subjectType: subjectTypeList.value[0].value,
  idNumber: "",
  idCardValidity: "",
  idCardFrontFile: [],
  idCardBackFile: [],
});
// 上传图片统一处理
const handleCardFrontFile = () => {
  identifyFaceCard();
};
const handleCardBackFile = () => {
  identifyBackCard();
};

const rules = reactive({
  mallName: [{ required: true, message: "所在商圈/商场", trigger: "blur" }],
  idNumber: [
    { required: true, message: "请输入法人代表身份证号码", trigger: "blur" },
    { validator: validateIdCard, trigger: "blur" },
  ],
  idCardValidity: [{ required: true, message: "请选择身份证有效期限", trigger: "blur" }],
  idCardFrontFile: [{ required: true, message: "请上传法定代表人身份证正面图片", trigger: "blur" }],
  idCardBackFile: [{ required: true, message: "请上传法定代表人身份证反面图片", trigger: "blur" }],
});

const submitForm = async () => {
  let formEl = proxy?.refs?.baseFormRef;
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let params = {
        ...ruleForm,
        idCardValidity:
          ruleForm.idCardValidity && ruleForm.idCardValidity.length
            ? ruleForm.idCardValidity.join(",")
            : null,
        idCardBackFile: JSON.stringify(ruleForm.idCardBackFile),
        idCardFrontFile: JSON.stringify(ruleForm.idCardFrontFile),
      };
      if (defaultId.value) {
        params.id = defaultId.value;
      }
      await saveOrUpdateEmployee(params);
      emit("submitSuccess");
      isEdit.value = false;
      ElMessage.success(`${defaultId.value ? "更新" : "保存"}成功`);
      getEmployeeEnterInfoFunc();
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * ocr 识别
 *
 *
 */
// 身份证正面
const identifyFaceCard = async () => {
  try {
    const data = await getIdCardFaceInfo({
      url: ruleForm?.idCardFrontFile[0]?.url,
    });
    ruleForm.legalRepresentative = data.data.name;
    ruleForm.idNumber = data.data.num;
  } catch (err) {
    console.log(err);
  }
};
// 身份证反面
const identifyBackCard = async () => {
  try {
    const data = await getIdCardBackInfo({
      url: ruleForm?.idCardBackFile[0]?.url,
    });
    ruleForm.idCardValidity = [data.data.startDate, data.data.endDate];
  } catch (err) {
    console.log(err);
  }
};
// 是否编辑
const isEdit = ref(false);
const disabled = computed(() => !isEdit.value);
const handleEdit = () => {
  if (isEdit.value) {
    submitForm();
  } else {
    isEdit.value = !isEdit.value;
  }
};

const defaultId = ref(null);
const auditStatus = ref(null);
const getEmployeeEnterInfoFunc = async () => {
  try {
    const data = await getEmployeeEnterInfo(userId.value);
    console.log(data);

    handleDefaultForm(data.data);
    defaultId.value = data.data.id;
    auditStatus.value = data.data.status;
    if (!data.data.idNumber) {
      isEdit.value = true;
    }
    if (data.data.status === MYINDEX_AUDIT_STATUS.FAILED) {
      openErrorMessage(data.data.remark);
    }
  } catch (err) {
    console.log(err);
  }
};
const openErrorMessage = (remark) => {
  ElNotification({
    title: "驳回原因",
    message: remark,
    type: "error",
    duration: 5000,
  });
};
const defaultMall = ref({
  mallNameId: "",
  mallName: "",
});
const handleDefaultForm = (data) => {
  ruleForm.subjectType = data.subjectType;
  defaultMall.value = {
    mallNameId: data.mallNameId,
    mallName: data.mallName,
  };
  ruleForm.idNumber = data.idNumber;
  ruleForm.idCardValidity = data.idCardValidity?.split(",");
  ruleForm.idCardFrontFile = JSON.parse(data.idCardFrontFile);
  ruleForm.idCardBackFile = JSON.parse(data.idCardBackFile);
};
onMounted(() => {
  getEmployeeEnterInfoFunc();
  console.log(isEdit.value);
});
</script>

<style lang="scss" scoped>
.form-container {
  width: 70%;
  margin: 0 auto;
}
</style>
